import MyModal from "@/components/MyModal";
import { changePwd } from "@/services/user/user";
import { getUerInfo } from "@/utils/info";
import { useBoolean } from "ahooks";
import { Form, Input, message } from "antd";

export default ({ open, close }) => {
  const {account } = getUerInfo() || {};
  const [form] = Form.useForm();
  const [loading, { toggle: toggleLoading }] = useBoolean(false);
  const onOk = async () => {
    const values = await form.validateFields();
    values.account = account;
    toggleLoading();
    try {
      await changePwd(values)
      message.success("修改成功");
      close();
    } finally {
      toggleLoading();
    }
  };

  return (
    <MyModal
      title={"修改密码"}
      open={open}
      close={close}
      onOk={onOk}
      confirmLoading={loading}
    >
      <Form form={form} wrapperCol={{ span: 24 }} layout="vertical">
        <Form.Item
          name="oldPassword"
          label="原密码"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input.Password placeholder="请输入原密码" />
        </Form.Item>
        <Form.Item
          name="newPassword"
          label="新密码"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Input.Password placeholder="请输入新密码" />
        </Form.Item>
        <Form.Item
          name="confirmPassword"
          label="确认密码"
          rules={[
            {
              required: true,
              validator: (rule, value, callback) => {
                if (value !== form.getFieldValue("newPassword")) {
                  callback("两次密码不一致");
                } else {
                  callback();
                }
              },
            },
          ]}
          dependencies={["newPassword"]}
        >
          <Input.Password placeholder="请输入确认密码" />
        </Form.Item>
      </Form>
    </MyModal>
  );
};
